package com.j.lemon.learn.thread.collectionNotSafe;

import com.rabbitmq.client.*;
import org.springframework.core.CollectionFactory;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeoutException;

/**
 * @Author lijunjun
 * @Date 2019-04-17 17:12
 * @Description Map的非线程安全的例子，和解决方法
 */
public class MapNotSafeDemo {
    public static void main(String[] args) throws IOException, TimeoutException {
//        Map<String,String> map = new HashMap<>();

//        使用ConcurrentHashMap
        Map<String,String> map = new ConcurrentHashMap<>();
        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0,6));
                System.out.println(map);
            },String.valueOf(i)).start();
        }
        ConnectionFactory factory = new ConnectionFactory();
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {

            }

            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {

            }
        });
        channel.addReturnListener(new ReturnCallback() {
            @Override
            public void handle(Return returnMessage) {

            }
        });

        channel.basicConsume("",false,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
    }
}
